package com.learn.aop.aspects;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Aspect
@Component
@Order(1) // Order控制切面的优先级，数值越小，优先级越高
public class LogAspect {

    @Pointcut("execution(* *..Calculator.*(..))")
    public void pointCut() {}

    @Before(value = "com.learn.aop.aspects.MyPointCut.pointCut()")
    public void printLogBeforeCore(JoinPoint joinPoint) {
        // 获取方法签名
        Signature signature = joinPoint.getSignature();
        // 获取方法名
        String methodName = signature.getName();

        // 获取实参列表
        Object[] args = joinPoint.getArgs();
        List<Object> argList = Arrays.asList(args);
        System.out.println(argList);
        System.out.println(methodName);
        System.out.println("[AOP前置通知]方法开始了");
    }

    @AfterReturning(
            value = "pointCut()",
            returning = "targetMethodReturnValue"
    )
    public void printLogAfterCoreSuccess(JoinPoint joinPoint, Object targetMethodReturnValue) {

        System.out.println(targetMethodReturnValue);
        System.out.println("[AOP[返回通知]方法成功结束了");
    }

    @AfterThrowing(
            value = "pointCut()",
            throwing = "targetMethodException"
    )
    public void printLogAfterCoreException(JoinPoint joinPoint, Throwable targetMethodException) {
        System.out.println("targetMethodException.getCause() = " + targetMethodException.getCause());
        System.out.println("targetMethodException.getMessage() = " + targetMethodException.getMessage());
        System.out.println("[AOP[异常通知] 方法抛异常了");
    }

    @After("pointCut()")
    public void printLogCoreFinallyEnd() {
        System.out.println("[AOP[后置通知] 方法最终结束了");
    }
}



